import { Toast } from "@nutui/nutui";
import { useStore as useUserStore } from "@/store/user";
import { $pay, $orderSingleRecordScreen } from "@/apis/api";
import { record } from 'rrweb';
import { useStore as useScreenRecordingStore } from '@/store/screenRecording';
import to from "await-to-js";

export default () => {
  const userStore = useUserStore();
  const screenRecordingStore = useScreenRecordingStore();
  const crateWeb = () => {
    let events: any[] = [];
    record({
      emit(event) {
        // 用任意方式存储 event
        events.push(event);
        screenRecordingStore.addEvents(events, 'pay');
      }
    })
  }
  const saveScreenRecord = async (order_no: string) => {
    let params: any = {};
    const event = encodeURIComponent(JSON.stringify(screenRecordingStore.events.pay));
    params.order_no = order_no;
    params.screen_record = event;
    params.scene = 'pay';
    Toast.loading('记录提交中...', {
      id: 'screenSave',
      duration: 0,
    })
    const [err, res]: any = await to($orderSingleRecordScreen(params));
    if (!err) {
      screenRecordingStore.initEvents('pay');
    }
    Toast.hide('screenSave');
  }
  // 支付调用
  const submit = (out_trade_no: string, order_no: string) => {
    screenRecordingStore.initEvents('pay');
    crateWeb();
    Toast.loading('支付调起中...', {
      id: 'pay',
      duration: 0,
    })
    let params = {
      app_type: 'wechat',
      pay_type: 'wechatpay',
      out_trade_no,
      open_id: userStore.user_info.open_id,
    };
    $pay(params).then((res: any) => {
      const payObj = res.data?.data || {};
      window.wx.ready(() => {
        window.wx.chooseWXPay({
          timestamp: payObj.timestamp,
          nonceStr: payObj.nonceStr,
          package: payObj.package,
          signType: payObj.signType,
          paySign: payObj.paySign,
          success: (payRes: any) => {
            Toast.success('支付成功');
            saveScreenRecord(order_no);
          },
          cancel: () => {
            Toast.fail('您已取消支付!');
          },
          fail: (payErr: any) => {
            Toast.fail(payErr.errMsg);
          },
        });
      });
    }).finally((err: any) => {
      Toast.hide('pay');
    })
  }
  return {
    submit,
  }
}